package service

import (
	"fmt"
	"kubernate-server/module"
	"net/http"
	"os"
	"strconv"
	"time"

	"kubernate-server/conf"

	"github.com/gin-gonic/gin"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

/**
 * Author: sbw
 * Description: Cluster operation
 * Date:20250927
 */

type ClustersService struct {
}

func returnFailMsg(ctx *gin.Context, msg string, returnCode string) {
	ctx.JSON(http.StatusBadRequest, gin.H{
		"code":   returnCode,
		"messge": msg,
	})
}
func returnSuccMsg(ctx *gin.Context, msg string) {
	ctx.JSON(http.StatusOK, gin.H{
		"code":   20000,
		"messge": msg,
	})
}

/*
*
新增k8s集群
*/
func (ClustersService) AddCluster(ctx *gin.Context) {
	clusterName := ctx.PostForm("clusterName")
	filename := clusterName + "_kubeconfig"
	// 指定保存路径
	savePath := conf.CLUSTER.Cluster.FilePath + filename
	var exist bool
	exist, err := (*ClusterDao).IsExist(nil, clusterName)
	if err != nil {
		returnFailMsg(ctx, "查询集群名称失败", "50000")
		return
	}
	if exist == true {
		returnFailMsg(ctx, "集群名称已存在", "50000")
		return
	}

	file, err := ctx.FormFile("file")
	if err != nil {
		fmt.Println(err.Error())
		returnFailMsg(ctx, "文件上传失败", "50000")
		return
	}
	// 保存文件
	if err := ctx.SaveUploadedFile(file, savePath); err != nil {
		returnFailMsg(ctx, "文件报存失败", "50000")
		return
	}
	if err := (*ClusterDao).InsertCluster(nil, module.ClusterAuth{
		ClusterName: clusterName,
		FilePath:    savePath,
		AuthType:    "1",
		IsDelete:    "0",
		Ct:          time.Now(),
		Ut:          time.Now(),
	}); err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	returnSuccMsg(ctx, "成功")
}

/*
*
切换k8s集群
*/
func (ClustersService) ChangeCluster(ctx *gin.Context) {
	clusterName := ctx.Param("clusterName")
	exist, err := (*ClusterDao).IsExist(nil, clusterName)
	if exist == false && err == nil {
		returnFailMsg(ctx, "集群不存在", "50000")
		return
	}
	kubeconfig := conf.CLUSTER.Cluster.FilePath + clusterName + "_kubeconfig"
	if _, err := os.Stat(kubeconfig); err != nil {
		returnFailMsg(ctx, "集群切换失败", "50000")
		return
	}
	config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	if err != nil {
		returnFailMsg(ctx, "集群切换失败", "50000")
		return
	}
	clientcmd, err := kubernetes.NewForConfig(config)
	if err != nil {
		returnFailMsg(ctx, "集群切换失败", "50000")
		return
	}
	conf.KuberConfigSet = clientcmd
	returnSuccMsg(ctx, "成功")
}

/*
查询k8s集群名称
*/
func (ClustersService) QueryClusters(ctx *gin.Context) {
	clusterList := (*ClusterDao).QueryClusters(nil)
	ctx.JSON(http.StatusOK, gin.H{
		"code":     20000,
		"messge":   "success",
		"clasters": clusterList,
	})
}

func (ClustersService) DeleteCluster(ctx *gin.Context) {
	id, err := strconv.ParseInt(ctx.Param("id"), 10, 0)
	fmt.Println(id)
	err = (*ClusterDao).DeleteCluster(nil, id)
	if err != nil {
		fmt.Println(err.Error())
		returnFailMsg(ctx, "集群删除失败", "50000")
		return
	}
	returnSuccMsg(ctx, "成功")
}
